package com.gdpu.pbss.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.gdpu.pbss.Constants.Constants;
import com.gdpu.pbss.DTO.ManagerDTO;
import com.gdpu.pbss.DTO.UserDto;
import com.gdpu.pbss.common.Result;
import com.gdpu.pbss.exception.ServiceException;
import com.gdpu.pbss.mapper.UserMapper;
import com.gdpu.pbss.pojo.Manager;
import com.gdpu.pbss.pojo.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gdpu.pbss.service.UserService;
import com.gdpu.pbss.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨
 * @since 2024-02-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser() ;
    }

    @Override
    public Boolean updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int deleteUser(Integer userId) {
        return userMapper.deleteUser(userId);
    }

    @Override
    public UserDto login(UserDto userDto) {
        User user = getUser(userDto);
        if (user!=null){
            BeanUtil.copyProperties(user,userDto);
            String token= TokenUtils.getUserToken(userDto.getUserId(),userDto.getPassward());
            userDto.setToken(token);
            return userDto;
        }else {
            throw new ServiceException(Constants.CODE_400,"用户名或密码错误");
        }

    }

    @Override
    public User register(UserDto userDto) {
        User one = getUser(userDto);
        if (one==null){
            one=new User();
            one.setUserName(userDto.getUserName());
            one.setPassward(userDto.getPassward());
            save(one);
        }else {
            throw new ServiceException(Constants.CODE_600,"用户已存在");
        }

        return one;
    }




    public User getUser(UserDto userDto){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",userDto.getUserName());
        queryWrapper.eq("passward",userDto.getPassward());
        User one;
        try {
            one=getOne(queryWrapper);
        }catch (Exception e){
            throw new ServiceException(Constants.CODE_500,"系统异常");
        }
        return one;
    }
}
